package com.security;

import com.alibaba.fastjson.JSON;
import com.pojo.vo.TokenVo;
import com.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Component
public class OtpAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    AuthenticationProxy authenticationProxy;
    @Autowired
    TokenService tokenService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String code = String.valueOf(authentication.getCredentials());
        boolean valid = authenticationProxy.checkOtp(username, code);
        if (valid) {
            //查询用户权限
            UserVo userVo = authenticationProxy.load(username);
            //创建令牌
            System.out.println("----------------------------------");
            TokenVo token = tokenService.createToken(((OtpAuthentication) authentication).getRememberMe(), userVo.getUser().getId(), userVo.getUsername(), JSON.toJSONString(userVo.getRoleList()), JSON.toJSONString(userVo.getPermissionList()));
            //验证通过之后不允许存如密码(credentials属性存入东西的话会自动忽略，为null)
            return new OtpAuthentication(token, token, userVo.getAuthorities());
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return OtpAuthentication.class.isAssignableFrom(authentication);
    }
}
